<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Mail;
use App\Models\Warnactset;
use App\Http\Requests\SystemRequest;
use DefaultCompany;
use App\Models\Changetable;
use App\Models\Company;
use Cache;

/**
 * 系统设置
 */

class SystemController extends Controller
{

    private $fields = [
        //声光
       'voice' => [ 
           'lig_sou_enable', 
           'wa_VLTermID',
        ],
        //3d
        'd3' => [ 
            'wa_3DPlatURL',
        ],
        //短信
        'sms' => [ 
            'wa_SmsPlatURL',
         ],
        //邮箱
        'email' => [ 
            'wa_emailusername', 
            'wa_emailpasswd',
            'wa_SMTPserver', 
        ],
    ];

    //升级
    private $upgrades = [
        'webapp_path',
        'backend_path',
        'service_path'
    ];
   
    /**
     * 系统配置
     */
    public function index(Request $request) {

        $user = $request->user();

        $cid = data_get($user, 'Co_ID')?data_get($user, 'Co_ID'):DefaultCompany::getCompanyField();

        $info = Warnactset::firstOrCreate(['Co_ID' => $cid]);

        $config = $this->formatFields($info);

        $upgrade = $this->getUpgradeInfo();

        return [ 'config'=> $config, 'upgrade'=> $upgrade];
    }

    //返回封装信息
    private function formatFields($values) {
        $result = [];
        foreach($this->fields as $k => $v) {
            if(!array_has($result, $k)) {
                $result[$k] = [];
            }
            foreach($v as $vv) {
                $result[$k][$vv] = data_get($values, $vv);
            }
        }
        return $result;
    }

    //获取配置字段
    private function getConfig($key) {
        if(!$key) return [];
        return array_get($this->fields, $key, []);
    }

    //更新到数据库
    private function updateData($request, $data) {

        $user = $request->user();

        $cid = data_get($user, 'Co_ID')?data_get($user, 'Co_ID'):DefaultCompany::getCompanyField();

        Warnactset::updateOrCreate([ 'Co_ID' => $cid ], $data);
    }

    //更新
    private function updateByKey($request, $key) {

        $fields = $this->getConfig($key);

        $data = $request->only($fields);

        if($key=='email') {
            $data['wa_emailbox'] = array_get($data, 'wa_emailusername');
        }

        $this->updateData($request, $data);
    }
    
    /**
     * 邮箱配置保存
     */
    public function storeEmail(SystemRequest $request) {
        $this->updateByKey($request, 'email');
    }
    
    /**
     * 短信配置保存
     */
    public function storeSms(SystemRequest $request) {
        $this->updateByKey($request, 'sms');
    }

    /**
     * 3d配置保存
     */
    public function store3d(SystemRequest $request) {
        $this->updateByKey($request, 'd3');
    }
    
    /**
     * 声光配置保存
     */
    public function storeVoice(SystemRequest $request) {
        $this->updateByKey($request, 'voice');
    }


    /**
     * 缓存更新
     */
    public function updateCache(SystemRequest $request) {
        $list = Company::select(['Co_ID'])->get();

        $cacheCompanyKey ='company:default';

        Cache::forget($cacheCompanyKey);

        $cacheAreaKey = 'company:area';
        
        foreach($list as $v) {
            Cache::forget($cacheAreaKey.':'.$v->Co_ID);
        }
    }

    /**
     * 版本升级
     */
    public function storeUpgrade(SystemRequest $request) {
       // $this->updateByKey($request, 'voice');
       $data = $request->only($this->upgrades);

       if(count($data)==0) {
           $this->error('请选择文件上传');
       }

      

       foreach($data as $k=>$v) {
        $info = Changetable::where('table', $k)->first();
        if(!$info) {
            Changetable::create([
                'table'=>$k,
                'value'=>$v, 
                'fields'=>'path', 
                'updatetime'=>date('Y-m-d H:i:s')
            ]);
            continue;
        }
        
        if($info->value!=$v) {
            $info->value = $v;
            if($v) {
                $info->updatetime = date('Y-m-d H:i:s');
            }
            $info->save();
        }

       }
    }

    /**
     * 获取升级信息
     */
    private function getUpgradeInfo() {
        $info = Changetable::whereIn('table', $this->upgrades)
        ->select(['table', 'value'])
        ->get()
        ->pluck('value', 'table')
        ->all();
        $result = [];
        foreach($this->upgrades as $v){
            $result[$v] = array_get($info, $v);
        }
        return $result;
    }
    
    /**
     * 测试邮箱
     */
    public function testsend() {
        $name = 'vilin';
        $configKeys = config('mail');
        $config = Cache::get($this->cacheKey);
        $config['from'] = ['address' => $config['username'], 'name' => strstr($config['username'], '@', true)];
        foreach ($configKeys as $key => $v) {
            config(['email.'.$key => array_get($config, $key, $v)]);
        }
        if(empty($config['to'])){
            return $this->error('请填写测试邮箱后再发送！');
        }
        $flag = Mail::send('emails.test', ['name' => $name], function($message) use($config) {
                    $to = $config['to'];
                    $message->to($to)->subject('邮件主题');
                });
        if ($flag) {
            return $this->success('发送邮件成功，请查收！');
        } else {
            return $this->error('发送邮件失败，请重试！');
        }
    }
    
    /**
     * 测试短信
     */
    public function testsendsms(Request $request) {
       $message = [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机号格式不正确',
       ];
       $this->validate($request, [
            'phone'=>['required', 'regex:/^1[35789]\d{9}$/' ],
        ], $message);
       
        $invoice = [
            'phone'=>$request->input('phone'),
            'content'=>'您好,当前验证码是: 123456',
        ];
        $user = $request->user();
        $flag = \App\Models\SmsSend::create([
                'Co_ID'=>$user?$user->Co_ID:null,
                'phone'=>$invoice['phone'],
                'msg'=>$invoice['content'],
                'sendtime'=>date('YmdHi')
            ]);
        if ($flag) {
            return $this->success('发送短信成功，请查收！');
        } else {
            return $this->error('发送短信失败，请重试！');
        }
    }
}
